package com.xuecheng.mybatis.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xuecheng.commons.utils.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyBatisPlusConfig {
    private static String [] tables = new String[]{"tb_dictionary","tb_category",
            "undo_log","tb_application","tb_company","tb_resource","tb_role_resource","tb_user_role"};
    //注册mybatis的插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //分页查询的插件
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        return interceptor;
    }

    //分页查询的插件配置
@Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
    return new PaginationInnerInterceptor(DbType.MYSQL);
    }

    /*
     * 多租户的插件配置文件
     * getTenantid   租户数据的来源
     *getTenantidColumn    拼接的sql语句租户字段
     * ignoreTable 判断表时候需要租户配置
     * */
    @Bean
    public TenantLineInnerInterceptor tenantLineInnerInterceptor() {
        return new TenantLineInnerInterceptor(new TenantLineHandler() {
            /*
            * 获取线程中企业的id
            * */

            @Override
            public Expression getTenantId() {
                Long companyId = AuthInfoHolder.getCompanyId();
                if (ObjectUtil.isEmpty(companyId)) {
                    return null;
                } else {
                    return new StringValue(companyId.toString());
                }
            }
/*
* 租户的字段
*
* */
            @Override
            public String getTenantIdColumn() {
                return  "company_id";
            }
//设置忽略的表  true忽略  false -拼接


            @Override
            public boolean ignoreTable(String tableName) {
                //是否要需要需要过滤某一张表
                if (ArrayUtil.contains(tables, tableName)) {
                    return true;
                }
                //拼接的sql多租户字段适应对应的值不能为空
                Expression tenantid = this.getTenantId();
                if (ObjectUtil.isEmpty(tenantid)) {
                    return true;
                }
                return false;
            }
        });
    }
}
